import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/push/jpush_utils.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';

class DeviceInfoNotifier extends StateNotifier<DeviceInfoVO> {
  DeviceInfoNotifier(this.ref)
      : super(SpUtil.getObject('deviceInfo') == null
            ? DeviceInfoVO()
            : DeviceInfoVO().fromJson(SpUtil.getObject('deviceInfo')!)) {}

  final Ref ref;

  void setDeviceInfo(DeviceInfoVO deviceInfo) {
    state = deviceInfo;
    SpUtil.putObject('deviceInfo', deviceInfo);
  }

  void removeDeviceInfo() {
    state = DeviceInfoVO();
    SpUtil.remove('deviceInfo');
  }

  /// 刷新设备信息
  Future<void> refresh(VoidCallback onSuccess) async {
    switchImei(state.imei ?? '', onSuccess);
  }

  /// 切换设备
  Future switchImei(String imei, VoidCallback onSuccess) async {
    // 切换设备，根据imei获取设备信息
    final res = await get<HomeDeviceInfoResp, HomeDeviceInfoResp>('/home/deviceInfo',
        queryParameters: {'imei': imei}, decodeType: HomeDeviceInfoResp());
    res.when(
        success: (HomeDeviceInfoResp resp) async {
          if (resp.code == 200) {
            if (resp.data == null || resp.data!.deviceInfo == null) {
              removeDeviceInfo();
              return;
            }
            setDeviceInfo(resp.data!.deviceInfo!);
            onSuccess();
          } else {
            removeDeviceInfo();
          }
        },
        failure: (String msg, int code) {});
  }

  /// 切换当前设备
  /// 比如，解绑当前设备时，在首页需要切换到另一台设备显示
  Future switchCurrentDevice(VoidCallback onSuccess) async {
    await switchImei('', () {});
    onSuccess();
  }
}
